<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Facebook extends Controller_Base_Frontend {

	protected $consumer;

	protected $token;

	public $view;

	public function before()
	{
		parent::before();

		// Load the configuration for this provider
		$config = Kohana::$config->load("oauth.facebook");

		// Create an consumer from the config
		$this->consumer = OAuth_Consumer::factory($config);

		if ($token = Cookie::get('oauth_token'))
		{
			// Get the token from storage
			$this->token = unserialize($token);
		} else{
			$this->token = FALSE;
		}
	}

	public function action_index()
	{
		if ($this->token AND $this->token->name === 'access')
		{
			Request::factory($this->request->uri(array('action' => 'facebook')))->execute()->body();
		}
		else
		{
			$this->response->body(HTML::anchor($this->request->uri(array('action' => 'login')), 'Login with Facebook'));
		}
	}

	public function action_login()
	{
		$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
			. $this->consumer->key . "&redirect_uri=" . urlencode($this->consumer->callback)."&scope=email";

		echo("<script> top.location.href='" . $dialog_url . "'</script>");
	}

	public function action_complete()
	{
		
		$code = isset($_REQUEST["code"])?$_REQUEST["code"]:"2.Ykm_ZhxmK4U_bGDV1RtQpQ__.3600.1299859200-100002125497095|mOciRbZGHO8f3Frgj0bBhjC5c28";

		$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
			. $this->consumer->key . "&redirect_uri=" . urlencode($this->consumer->callback) . "&client_secret="
			. $this->consumer->secret . "&code=" . $code;

		$access_token = file_get_contents($token_url);

		Cookie::set('oauth_token', serialize($access_token));

		$graph_url = "https://graph.facebook.com/me?" . $access_token;
		$facebookUser = json_decode(file_get_contents($graph_url));

		$facebookLogin = ORM::factory("facebook_Login", array("facebook_id" => $facebookUser->id));

		if("" != $facebookLogin){
			Auth::instance()->force_login($facebookLogin->users);

			Request::current()->redirect("/");
		}

		if(preg_match_all('/@proxymail\.facebook\.com/', $facebookUser->email, $matchesArray)){
			$this->view->content = Smarty_View::factory('facebookEmail.tpl');
			$this->view->content->name = $facebookUser->name;
			$this->view->content->facebook_id = $facebookUser->id;
			$this->response->body($this->view);
		} else{
			Request::factory($this->request->uri(array('action' => 'create_account')))
					->post("facebook_id", $facebookUser->id)
					->post("email", $facebookUser->email)
					->post("name", $facebookUser->name)
					->post("confirmed", "yes")
					->execute();
		}

	}

	public function action_create_account(){

		$post = $this->request->post();
		$user = ORM::factory("user", array('email' => $post['email']));
		if("" == $user){
			try{
				$user = ORM::factory("user");
				$password = text::random("alnum", 8);
				$user->create_user(array("email" => $post['email'],
										 "name"  => $post['name'],
										 "password"=>$password,
										 "password_confirm" => $password,
										),
									array('email', 'password', 'name')
								  );
				$user->add('roles', ORM::factory('role')->where('name', '=', 'login')->find());
				Email::send($user->email, "Conta", "Sua senha é: ".$password);
			}catch(ORM_Validation_Exception $e){
				$this->response->body(Json_View::factory(array("content"=>  $e->errors())));
				return;
			}catch(Exception $e){
				$errors = array("email" => $e->getMessage());
				$this->response->body(Json_View::factory(array("content"=>  $errors)));
				die();
			}
		}
		$post['users_id'] = $user->id;

		$facebookLogin = ORM::factory("facebook_Login", array("facebook_id" => $post['facebook_id']));
		if(FALSE != $facebookLogin){
			$facebookLogin = ORM::factory("facebook_Login")->values($post, array("facebook_id", "users_id"));
			$facebookLogin->save();
		}

		Auth::instance()->force_login($user);

		Request::current()->redirect("/");
	}

} // End OAuth_Facebook